<template>
  <div class="app-container">
    <el-card>
      <!-- 头部 -->
      <div slot="header">
        <span>试题录入</span>
      </div>
      <el-form
        ref="addForm"
        :rules="addrules"
        :model="addForm"
        label-width="80px"
      >
        <!-- 学科 -->
        <el-form-item label="学科" prop="subjectID">
          <el-select
            @change="subjectChoice"
            v-model="addForm.subjectID"
            placeholder="请选择"
          >
            <el-option
              v-for="item in subjectIDList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 目录 -->
        <el-form-item label="目录" prop="catalogID">
          <el-select v-model="addForm.catalogID" placeholder="请选择">
            <el-option
              v-for="item in catalogIDList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 企业 -->
        <el-form-item label="企业" prop="enterpriseID">
          <el-select v-model="addForm.enterpriseID" placeholder="请选择">
            <el-option v-for="item in companysList" :key="item.id" :label="item.company" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <!-- 城市 -->
        <el-form-item label="城市" class="city" prop="city">
          <el-select @change="provinceChoice" v-model="addForm.province" placeholder="请选择">
            <el-option v-for="(item,index) in provinceList" :key="index" :label="item" :value="item"></el-option>
          </el-select>
          <el-select v-model="addForm.city" placeholder="请选择">
            <el-option v-for="(item,index) in cityList" :key="index" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <!-- 方向 -->
        <el-form-item label="方向" prop="direction">
          <el-select v-model="addForm.direction" placeholder="请选择">
            <el-option v-for="(item,index) in directionList" :key="index" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <!-- 题型 -->
        <el-form-item label="题型" prop="questionType">
          <el-radio v-model="addForm.questionType" label="1">单选</el-radio>
          <el-radio v-model="addForm.questionType" label="2">多选</el-radio>
          <el-radio v-model="addForm.questionType" label="3">简答</el-radio>
        </el-form-item>
        <!-- 难度 -->
        <el-form-item label="难度" prop="difficulty">
          <el-radio v-model="addForm.difficulty" label="1">简单</el-radio>
          <el-radio v-model="addForm.difficulty" label="2">一般</el-radio>
          <el-radio v-model="addForm.difficulty" label="3">困难</el-radio>
        </el-form-item>
        <!-- 题干 -->
        <el-form-item label="题干" style="margin-bottom: 50px" prop="question">
          <quill-editor
            style="height: 200px"
            v-model="addForm.question"
            ref="myQuillEditor"
            :options="editorOption"
          >
          </quill-editor>
        </el-form-item>
        <!-- 选项 -->
        <el-form-item
          class="option"
          v-if="+addForm.questionType !== 3"
          label="选项"
          style="width: 400px"
        >
          <div
            v-for="item in addForm.options"
            :key="item.ascii"
            style="
              display: flex;
              justify-content: space-between;
              align-items: center;
            "
          >
            <el-radio
              v-if="+addForm.questionType === 1"
              v-model="radioCheck"
              :label="item.code"
              >{{ item.code }} ：
              <el-input style="width: 240px" v-model="item.title"></el-input
            ></el-radio>
            <el-checkbox v-else v-model="item.isRight"
              >{{ item.code }} ：
              <el-input v-model="item.title" style="width: 240px"></el-input
            ></el-checkbox>
            <!-- 上传图片 -->
            <imgComponents
              :img.sync="item.img"
              class="imgComponents"
            ></imgComponents>
          </div>
        </el-form-item>
        <!-- 新增按钮 -->
        <el-form-item v-if="+addForm.questionType !== 3">
          <el-button
            @click="addOption"
            :disabled="+addForm.questionType === 1"
            type="danger"
          >
            + 新增选项
          </el-button>
        </el-form-item>
        <!-- 解析视频 -->
        <el-form-item label="解析视频" style="width: 480px">
          <el-input v-model="addForm.videoURL"></el-input>
        </el-form-item>
        <!-- 答案解析 -->
        <el-form-item
          label="答案解析"
          style="margin-bottom: 50px"
          prop="answer"
        >
          <quill-editor
            style="height: 200px"
            v-model="addForm.answer"
            ref="myQuillEditor"
            :options="editorOption"
          ></quill-editor>
        </el-form-item>
        <!-- 题目备注 -->
        <el-form-item label="题目备注" style="width: 480px">
          <el-input type="textarea" v-model="addForm.remarks"></el-input>
        </el-form-item>
        <!-- 试题标签 -->
        <el-form-item label="试题标签">
          <el-select v-model="addForm.tags" placeholder="请选择">
            <el-option
              v-for="item in tagsList"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 确认按钮 -->
        <el-form-item>
          <el-button @click="onSubmit" type="primary"> 确认提交 </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import imgComponents from '@/module-hmmm/components/imgComponents.vue'
import { simple as subjectsSimple } from '@/api/hmmm/subjects.js'
import { simple as directorysSimple } from '@/api/hmmm/directorys.js'
import { simple as tagsSimple } from '@/api/hmmm/tags.js'
import { list as getCompanys } from '@/api/hmmm/companys.js'
import { provinces, citys } from '@/api/hmmm/citys.js'
import { direction } from '@/api/hmmm/constants.js'
import { add, detail, update } from '@/api/hmmm/questions.js'

export default {
  components: {
    imgComponents
  },
  data () {
    return {
      editorOption: {
        placeholder: ''
      },
      subjectchecked: false,
      subjectIDList: [],
      catalogIDList: [],
      tagsList: [],
      companysList: [],
      provinceList: [],
      cityList: [],
      directionList: direction,
      addForm: {
        number: '', // 试题编号
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        city: '', // 地区
        direction: '', // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 问题
        options: [
          { ascii: 65, code: 'A', title: '', img: '', isRight: true }, // 代码  标题  图片URL 是否正确
          { ascii: 66, code: 'B', title: '', img: '', isRight: false }, // 代码  标题  图片URL 是否正确
          { ascii: 67, code: 'C', title: '', img: '', isRight: false }, // 代码  标题  图片URL 是否正确
          { ascii: 68, code: 'D', title: '', img: '', isRight: false } // 代码  标题  图片URL 是否正确
        ], // 选项
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: '', // 试题标签
        isPerfect: '' // 是否精选 后台自动生成（忽略）
      },
      addrules: {
        subjectID: [{ required: true, message: '请选择', trigger: 'change' }],
        catalogID: [{ required: true, message: '请选择', trigger: 'change' }],
        enterpriseID: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        province: [{ required: true, message: '请选择', trigger: 'change' }],
        city: [{ required: true, message: '请选择', trigger: 'change' }],
        direction: [{ required: true, message: '请选择', trigger: 'change' }],
        questionType: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        difficulty: [{ required: true, message: '请选择', trigger: 'change' }],
        question: [{ required: true, message: '请填写', trigger: 'change' }],
        answer: [{ required: true, message: '请填写', trigger: 'change' }]
      },
      radioCheck: 'A'
    }
  },
  watch: {
    // 监听单选框
    radioCheck: {
      handler (newVal) {
        this.addForm.options.forEach((item) => {
          if (item.code === newVal) {
            item.isRight = true
          } else {
            item.isRight = false
          }
        })
        // console.log(this.addForm.options)
      },
      immediate: true
    }
  },
  created () {
    this.getSubjectIDList()
    this.getCompanys()
    this.getProvince()
    this.dataBackfill()
  },
  methods: {
    // 添加选项
    addOption () {
      const index = this.addForm.options.length - 1
      this.addForm.options.push({
        ascii: this.addForm.options[index].ascii + 1,
        code: String.fromCharCode(this.addForm.options[index].ascii + 1),
        title: '',
        img: '',
        isRight: false
      })
    },
    onSubmit () {
      this.$refs.addForm.validate(async (valid) => {
        if (!valid) return this.$message.error('请正确填写')
        // 删除对象中的某一项
        // this.addForm.options.forEach(item => {
        //   delete item.ascii
        // })
        // console.log(this.addForm)
        let res = {}
        if (!this.$route.query.id) {
          res = await add(this.addForm)
        } else {
          res = await update(this.addForm)
        }
        // console.log(res)
        if (res.status !== 200) return this.$message.error('添加失败')
        this.$message.success('成功')
        this.$refs.addForm.resetFields()
        this.$router.push('/questions/list')
      })
    },
    // 选择了学科才可以选择对应的目录
    subjectChoice (val) {
      this.catalogIDList = []
      this.tagsList = []
      this.addForm.catalogID = ''
      this.addForm.tags = ''
      this.getCatalogIDList(val)
      this.getTagsList(val)
    },
    // 选择了省份才能选择城市
    provinceChoice (val) {
      this.cityList = []
      this.addForm.city = ''
      this.getCitys(val)
    },
    // 获取学科
    async getSubjectIDList () {
      const res = await subjectsSimple()
      // console.log(res)
      if (res.status !== 200) return
      this.subjectIDList = res.data
    },
    // 获取目录
    async getCatalogIDList (val) {
      const res = await directorysSimple({ subjectID: val })
      // console.log(res)
      if (res.status !== 200) return
      this.catalogIDList = res.data
    },
    // 获取标签
    async getTagsList (val) {
      const res = await tagsSimple({ subjectID: val })
      // console.log(res)
      if (res.status !== 200) return
      this.tagsList = res.data
    },
    // 获取企业
    async getCompanys () {
      const res = await getCompanys()
      // console.log(res)
      if (res.status !== 200) return
      // console.log(res.data.items)
      this.companysList = res.data.items
    },
    // 获取城市
    getProvince () {
      const res = provinces()
      // console.log(res)
      this.provinceList = res
    },
    // 获取地级市
    getCitys (val) {
      const res = citys(val)
      // console.log(res)
      this.cityList = res
    },
    // 数据回填
    async dataBackfill () {
      if (!this.$route.query.id) return
      const res = await detail(this.$route.query)
      // console.log(res.data)
      if (res.status !== 200) return
      this.addForm = res.data
      // console.log(this.addForm)
      this.addForm.options.forEach(item => {
        item.ascii = item.code.charCodeAt()
      })
      this.addForm.options.sort((a, b) => {
        return a.ascii - b.ascii
      })
    }
  }
}
</script>

<style scoped lang="scss">
// ::v-deep .el-input__inner{
//   width: 500px;
// }

::v-deep .el-select .el-input__inner {
  width: 400px;
}
::v-deep .city .el-select .el-input__inner {
  width: 198px;
  margin-right: 5px;
}
.el-form {
  padding: 10px 50px;
}
.option > div {
  margin: 20px 0;
}
.imgComponents {
  display: inline-block;
}
::v-deep .ql-toolbar.ql-snow + .ql-container.ql-snow {
  height: 130px;
}
</style>
